﻿var http = require('http');
var querystring = require('querystring');
//var multipart = require('multipart');

function writeResponse(res, data) {
    var total = 0;
    for (var fruit in data) {
        if (!isNaN(data[fruit])) {
            total += Number(data[fruit]);
        }

    }
    data.total = total;
    var jsonData = JSON.stringify(data);
    res.writeHead(200, 'OK', {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': 'http://localhost:3210'
    });
    res.write(jsonData);
    res.end();
}

http.createServer(function (req, res) {
    console.log('[200] ' + req.method + ' to ' + req.url);
    if (req.method == 'OPTIONS') {
        res.writeHead(200, 'OK', {
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Methods': '*',
            'Access-Control-Allow-Origin': '*'
        });
        res.end();
    } else if (req.url == '/form' && req.method == 'POST') {
        var dataObj = new Object();
        var contentType = req.headers['content-type'];
        var fullBody = '';
        if (contentType) {
            if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
                req.on('data', function (chunk) {
                    fullBody += chunk.toString();
                });
                req.on('end', function () {
                    var dBody = querystring.parse(fullBody);
                    dataObj.bananas = dBody['bananas'];
                    console.log(dataObj.bananas);
                    dataObj.apples = dBody['apples'];
                    dataObj.cherries = dBody['cherries'];
                    writeResponse(res, dataObj);
                });
            } else if (contentType.indexOf('application/json') > -1) {
                req.on('data', function (chunk) {
                    fullBody += chunk.toString();
                });
                req.on('end', function () {
                    dataObj = JSON.parse(fullBody);
                    writeResponse(res, dataObj);
                });
            } else if (contentType.indexOf('multipart/form-data') > -1) {
                //var partName;
                //var partType;
                //var parser = new multipart.parser();
                //parser.boundary = '--' + req.headers['content-type'].substring(30);
                //parser.onpartbegin = function (part) {
                //    partName = part.nanme;
                //    partType = part.contentType;
                //}
                req.on('data', function (chunk) {
                    fullBody += chunk.toString();
                });
                req.on('end', function () {
                    dataObj = JSON.parse(fullBody);
                    writeResponse(res, dataObj);
                });
            }
        }
    }
}).listen(8080);